#if UNITY_EDITOR
using UnityEngine;
using UnityEditor;
using System.IO;
using UnityEditor.IMGUI.Controls;

namespace MeEditor
{
    /// <summary>
    /// Prefab预览器 - 为prefab对象提供预览功能
    /// </summary>
    [CustomPreview(typeof(GameObject))]
    public class UIPreview : ObjectPreview
    {
        private Texture previewTexture;
        private bool isPrefab = false;
        private string prefabPath;
        private string previewPath;
        private float m_ZoomFactor = 1.0f;
        private Vector2 m_PreviewDir = new Vector2(120, -20);
        private bool isInitialized = false;
        
        // 旋转控制
        private bool m_Dragging = false;
        private Vector2 m_StartPosition;
        private Vector2 m_StartRotation;

        private void Initialize()
        {
            if (isInitialized) return;
            
            // 检查当前对象是否为Prefab
            GameObject gameObject = target as GameObject;
            if (gameObject != null)
            {
                prefabPath = AssetDatabase.GetAssetPath(gameObject);
                // Debug.Log("Initialize>>"+gameObject.name);
                if (!string.IsNullOrEmpty(prefabPath) && prefabPath.EndsWith(".prefab"))
                {
                    isPrefab = true;
                    string prefabName = Path.GetFileNameWithoutExtension(prefabPath);
                    previewPath = Configure.ResAssetsPath + "/Preview/" + prefabName + ".png";
                    
                    // 加载已有预览图
                    if (File.Exists(previewPath))
                    {
                        previewTexture = UIEditorHelper.LoadTextureInLocal(previewPath);
                    }
                }
                //选中图片预设后会有警告，暂时不知道为什么
            }
            
            isInitialized = true;
        }
        public override bool HasPreviewGUI()
        {
            Initialize();
            return isPrefab;
        }

        public override GUIContent GetPreviewTitle()
        {
            return new GUIContent("预设预览");
        }

        public override void OnPreviewGUI(Rect r, GUIStyle background)
        {
            if (!isPrefab)
            {
                EditorGUI.LabelField(r, "不是预设，无法预览");
                return;
            }
            // 显示预览图
            if (previewTexture != null)
            {
                // 计算预览图的绘制区域
                float maxSize = Mathf.Min(r.width, r.height);
                float ratio = (float)previewTexture.width / previewTexture.height;
                float width = ratio >= 1 ? maxSize : maxSize * ratio;
                float height = ratio >= 1 ? maxSize / ratio : maxSize;
                
                // 居中绘制
                Rect previewRect = new Rect(
                    r.x + (r.width - width) * 0.5f,
                    r.y + (r.height - height) * 0.5f,
                    width, height);
                
                // 绘制背景
                EditorGUI.DrawRect(r, new Color(0.3f, 0.3f, 0.3f, 1.0f));
                
                // 绘制预览图
                GUI.DrawTexture(previewRect, previewTexture, ScaleMode.ScaleToFit);
            }
        }


        public override void OnPreviewSettings()
        {
            if (GUILayout.Button("重置视图", EditorStyles.miniButton))
            {
                m_PreviewDir = new Vector2(120, -20);
                m_ZoomFactor = 1.0f;
            }

            if (isPrefab)
            {
                if (GUILayout.Button("生成预览图", EditorStyles.miniButton))
                {
                    GeneratePreview();
                }

                if (previewTexture != null && GUILayout.Button("刷新", EditorStyles.miniButton))
                {
                    previewTexture = null;
                    if (File.Exists(previewPath))
                    {
                        previewTexture = UIEditorHelper.LoadTextureInLocal(previewPath);
                    }
                }
            }
        }

        private void GeneratePreview()
        {
            if (!isPrefab) return;

            GameObject prefabObject = target as GameObject;
            if (prefabObject == null) return;
            
            // 确保预览目录存在
            string previewDir = Path.GetDirectoryName(previewPath);
            if (!Directory.Exists(previewDir))
            {
                Directory.CreateDirectory(previewDir);
            }

            // 生成预览图
            Texture previewTex = UIEditorHelper.GetAssetPreview(prefabObject);
            if (previewTex != null)
            {
                // 保存为PNG
                UIEditorHelper.SaveTextureToPNG(previewTex, previewPath);
                
                // 更新预览纹理
                previewTexture = UIEditorHelper.LoadTextureInLocal(previewPath);
                
                // 刷新资源
                AssetDatabase.Refresh();
                
                EditorUtility.DisplayDialog("成功", "预览图生成成功", "确定");
            }
            else
            {
                EditorUtility.DisplayDialog("错误", "无法为该预设生成预览图", "确定");
            }
        }

        public override void Cleanup()
        {
            base.Cleanup();
        }
    }
}
#endif
